import java.io.IOException;
import java.net.ServerSocket;
import java.util.ArrayList;
import java.util.Timer;
import java.util.TimerTask;

public class RISCServer {
	
	static ArrayList<Player> clients;
	static ServerSocket listener;
	static int id = 0;
	static RISC game;
	static int time = 5; //minutes for timer, just an example time
	static ArrayList<Order> orders;
	
	static Thread receiveOrders = new Thread() {
		public void run() {
			for(Player p : clients) {
				try {
					//client.StartTurn(
					game.SendText("Timer started!", p.getSocket());
				} catch (IOException e) {
					System.out.println("Telling clients time started failure: " + e.getMessage() + "\n");
				}
			}
			Timer turnTimer = new Timer();
			turnTimer.schedule(new TimerTask() {
				public void run() {
					//this is implemented wrong, threads don't work like this
					//change it to listen to arbitrary thread, recognize which client send the list
					for(Player p : clients) {
						try {
						ArrayList<Order> tempOrders = game.receiveOrders(p.getSocket());
						for(Order o : tempOrders)
							orders.add(o);
						} catch (ClassNotFoundException | IOException e) {
							System.out.println("TimerTask order receive failure " + e.getMessage() + "\n");
						} 
					}
				}
			}, time * 1000);
		}
	};
	
	static Thread acceptConnections = new Thread() {
		public void run() {
			while(true) {
				try {
					clients.add(new Player(listener.accept(), id++));
				} catch(IOException ioe) {
					System.out.println("Client accept failure: " + ioe.getMessage() + "\n");
				}
			}
		}
	};
	
	public static void main(String[] args) throws IOException {
		int id = 0;
		ServerSocket listener = new ServerSocket(2122);
		try {
			while(true) {
				game = new RISC();
				//when a certain number of players are here, start the game
				acceptConnections.setDaemon(true);
				acceptConnections.start();
				//setup the game
				game.setupMap(id, clients);
				//setup turn mechanism
				receiveOrders.setDaemon(true);
				receiveOrders.start();
			}
		} finally {
			listener.close();
		}
	}
}